package com.hls.zfbai.modules.business.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hls.zfbai.core.utils.CommonConstants;
import com.hls.zfbai.core.utils.HttpClientUtil;
import com.hls.zfbai.core.utils.XmlUtils;
import com.hls.zfbai.modules.business.entity.*;
import com.hls.zfbai.modules.business.entity.hlwyy.JybgEventReqParam;
import com.hls.zfbai.modules.common.dao.CommonMapper;
import com.hls.zfbai.modules.common.entity.GyXtcs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class JybgPushService {
    @Resource
    private MqPtJybgService mqPtJybgService;
    @Resource
    private ZfbAiService zfbAiService;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private MsYj01Service msYj01Service;
    @Resource
    private YjZy01Service yjZy01Service;

    @Scheduled(fixedRate = 1000)
    public void run() {
        LocalDateTime localDateTime = LocalDateTime.now();
        QueryWrapper<MqPtJybg> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("JLXH","SELECT JLXH FROM MQ_PT_JYBG WHERE JLSJ > SYSDATE - 5/1440 AND TSBZ = 0");
        List<MqPtJybg> mqPtJybgList = mqPtJybgService.list(queryWrapper);

        log.info("获取未推送的检验报告...");

        if(!CollectionUtils.isEmpty(mqPtJybgList)) {
            log.info("获取未推送的检验报告，共获取到信息数：{}条", mqPtJybgList.size());
            for(MqPtJybg mqPtJybg : mqPtJybgList) {
                this.sendWx(mqPtJybg);
                //更新推送状态
                mqPtJybg.setTsbz(1);
                mqPtJybg.setTssj(localDateTime);
                mqPtJybgService.updateById(mqPtJybg);
            }
        } else {
            log.info("获取未推送的检验报告，共获取到信息数：0条");
        }
    }

    /**
     * 报告出具推送（支付宝AI陪诊）
     * @param mqPtJybg
     */
    public void bgcj(MqPtJybg mqPtJybg) {
        GyXtcs qycsCs = new GyXtcs("1", "ZFBAI_SERVICE_SFQY", "0", "支付宝AI云陪诊接口是否启用");
        commonMapper.getXtcs(qycsCs);
        String qycs = qycsCs.getCSZ();
        GyXtcs qyghCs = new GyXtcs("1", "ZFBAI_SERVICE_SFQY_JYBG", "0", "支付宝AI云陪诊接口是否启用");
        commonMapper.getXtcs(qyghCs);
        String qyjy = qyghCs.getCSZ();

        if(CommonConstants.YES.equals(qycs) && CommonConstants.YES.equals(qyjy)) {
            String jzlx = this.getJzlx(mqPtJybg);
            if(CommonConstants.YES.equals(jzlx)) {
                String tmh = mqPtJybg.getBarCodeNo();
                if(StringUtils.isNotBlank(tmh)) {
                    Map<String, Object> msYj01 = zfbAiService.jybgcj(tmh);
                    if(!Objects.isNull(msYj01)) {
                        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                        LocalDateTime localDateTime = LocalDateTime.now();
                        String now = dateTimeFormatter.format(localDateTime);
                        String zlxmmc = msYj01.getOrDefault("ZLXMMC", "").toString();
                        if(zlxmmc.charAt(zlxmmc.length() - 1) == ',') {
                            zlxmmc = zlxmmc.substring(0, zlxmmc.length() - 1);
                        }

                        BgcjParam bgcjParam = new BgcjParam();
                        bgcjParam.setTradeCode("1001");
                        bgcjParam.setDatasetCode("HDSD.MZJZJL");
                        bgcjParam.setMedHosCode(msYj01.getOrDefault("YQSB", "1").toString());
                        bgcjParam.setMzlsh(msYj01.getOrDefault("JZXH", "0").toString());
                        bgcjParam.setGhlsh(msYj01.getOrDefault("GHXH", "0").toString());
                        bgcjParam.setSjlx("bgcj");
                        bgcjParam.setSjbm(tmh + "_bgcj");
                        bgcjParam.setSjfssj(now);
                        bgcjParam.setScbs("0");
                        bgcjParam.setSjgxsj(now);
                        bgcjParam.setSjxmdm(msYj01.getOrDefault("YJXH", "0").toString());
                        bgcjParam.setSjxmmc(zlxmmc);
                        bgcjParam.setBgdh(mqPtJybg.getReportNo());
                        bgcjParam.setBgdmc(zlxmmc + "报告结果");
                        bgcjParam.setTxnr(zlxmmc + "报告已出，请及时查看");
                        //推送接口
                        zfbAiService.bgcj(bgcjParam);
                    }
                }
            }
        }
    }

    /**
     * 报告推送微信
     * @param mqPtJybg
     */
    public void sendWx(MqPtJybg mqPtJybg) {
        String jzlx = this.getJzlx(mqPtJybg);
        String tmh = mqPtJybg.getBarCodeNo();
        if(StringUtils.isNotBlank(tmh) && StringUtils.isNotBlank(jzlx)) {
            JybgEventReqParam jybgEventReqParam = new JybgEventReqParam();
            jybgEventReqParam.setEventNo(UUID.randomUUID().toString().replace("-", ""));
            jybgEventReqParam.setEventType("lisReportCompleted");
            JybgEventReqParam.JybgEventData jybgEventData = new JybgEventReqParam.JybgEventData();
            jybgEventData.setReportId(mqPtJybg.getReportNo());
            jybgEventData.setExameDate(mqPtJybg.getTestDate());
            jybgEventData.setReportDate(mqPtJybg.getReportDate());
            jybgEventData.setReportTitle(mqPtJybg.getSampleTypeName());

            if(CommonConstants.COMMON_NUMBER_ONE.equals(jzlx)) {
                MsYj01 msYj01 = msYj01Service.getById(tmh);
                if(!Objects.isNull(msYj01)) {
                    jybgEventData.setClinicSeq(msYj01.getJzxh() == null?"":msYj01.getJzxh().toString());
                    jybgEventData.setPatientId(msYj01.getBrid().toString());
                }
            } else {
                YjZy01 yjZy01 = yjZy01Service.getById(tmh);
                if(!Objects.isNull(yjZy01)) {
                    jybgEventData.setInpatientId(yjZy01.getZyhm());
                }
            }

            jybgEventReqParam.setEventData(jybgEventData);
            String param = XmlUtils.convertToXml(jybgEventReqParam);
            log.info("检验报告推送微信，入参：{}", param);
            GyXtcs urlXtcs = new GyXtcs("1", "SEND_WXZYD_URL", "http://192.168.230.20:6888", "微信指引单接口路径");
            commonMapper.getXtcs(urlXtcs);
            String url = urlXtcs.getCSZ();
            GyXtcs methodXtcs = new GyXtcs("1", "SEND_WXZYD_METHOD", "/interface-service-v3/notify", "微信指引单接口方法");
            commonMapper.getXtcs(methodXtcs);
            String method = methodXtcs.getCSZ();
            String rsp = HttpClientUtil.postMethod(url + method, param, "", "");
            log.info("检验报告推送微信，出参：{}", rsp);
        }
    }

    public String getJzlx(MqPtJybg mqPtJybg) {
        String testPatResourceCode = mqPtJybg.getTestPatResourceCode();
        if(CommonConstants.COMMON_NUMBER_ONE.equals(testPatResourceCode)) {
            return CommonConstants.COMMON_NUMBER_ONE;
        } else if(CommonConstants.COMMON_NUMBER_THREE.equals(testPatResourceCode)) {
            return CommonConstants.COMMON_NUMBER_TWO;
        } else {
            return CommonConstants.COMMON_STRING_EMPTY;
        }
    }

}